↜ Back to index Introduction to Numerical Analysis 1
Solution Lecture b3
Exercise 1
! Solve the heat equation with periodic boundary condition
implicit none
integer, parameter :: M = 10
real, parameter :: pi = 4. * atan(1.)
integer n, k, nmax
real h, tau, x
real, dimension(0:M-1) :: u, v
= 1. / M
h = h * h / 4.
tau = 0.125 / tau
nmax
do k=0, M-1
= k * h
x = cos(2 * pi * x)
u(k) print *, 0., x, 0.
end do
print *
do n=0, nmax-1
do k = 0, M-1
= u(k) + (tau / (h * h)) * (u(mod(k + M - 1, M)) &
v(k) - 2 * u(k) + u(mod(k + 1, M)))
end do
do k = 0, M-1
print *, (n + 1) * tau, k * h, abs(v(k) - exp(-4*pi**2*(n+1)*tau) * cos(2. * pi * k * h))
end do
print *
= v
u end do
end
Exercise 2
implicit none
integer, parameter :: M = 10
integer n, k, nmax
real h, tau, x, a, b
real, dimension(0:M) :: u, v, error
= 1. / M
h = h * h / 4.
tau = 0.5 / tau
nmax
! Initial data u_0 = 0
do k = 0, M
= k * h
x = x * (1 - x)
u(k) enddo
! Print the initial error (0)
call printstep(0., 0. * u)
= 1
a = -1
b
do n=0, nmax-1
0) = u(0) + 2 * tau / (h * h) * (u(1) - u(0) - h * a)
v(do k = 1, M-1
= u(k) + (tau / (h * h)) * (u(k - 1) - 2 * u(k) + u(k + 1))
v(k) end do
= u(M) + 2 * tau / (h * h) * (u(M-1) - u(M) + h * b)
v(M)
do k = 0, M
= k * h
x = abs(v(k) - x * (1 - x) + 2 * (n + 1) * tau)
error(k) enddo
call printstep((n+1) * tau, error)
= v
u end do
contains
! Prints the values of the solution at a given time step
subroutine printstep(tn, un)
real tn
real, dimension(0:M) :: un
integer k
do k = 0, M
print *, tn, k * h, un(k)
end do
! print an empty line (needed for gnuplot)
print *
end subroutine
end
Exercise 2
implicit none
integer, parameter :: M = 10
integer n, k, nmax
real h, tau, x, f
real, dimension(0:M) :: u, v
= 1. / M
h = h * h / 4.
tau = 0.5 / tau
nmax
! Initial data u_0 = 0
= 0.
u ! Print the initial data
call printstep(0., u)
do n=0, nmax-1
0) = u(0)
v(do k = 1, M-1
= 10 - 20 * abs(k * h - 0.5)
f = u(k) + (tau / (h * h)) * (u(k - 1) - 2 * u(k) + u(k + 1)) + tau * f
v(k) end do
= u(M)
v(M)
call printstep((n+1) * tau, v)
= v
u end do
contains
! Prints the values of the solution at a given time step
subroutine printstep(tn, un)
real tn
real, dimension(0:M) :: un
integer k
do k = 0, M
print *, tn, k * h, un(k)
end do
! print an empty line (needed for gnuplot)
print *
end subroutine
end